package com.xiubai.appforpda.jack.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.xiubai.appforpda.App;


/**
 * A share preference helper class for accessing preference saved in
 * core_share.xml
 * 
 */
public class SharedPreferenceTool {
	/** share preference file to save */
	public static final String SHARE_DATA_FILE_NAME = "appforpda";
	public static final String COOKIE_KEY = "COOKIE_KEY";
    private static SharedPreferenceTool instance = null;
	private SharedPreferences mSharedPreferences;

	private SharedPreferenceTool() {
	}

	public synchronized static SharedPreferenceTool getInstance() {
		if (instance == null) {
			instance = new SharedPreferenceTool();
			Context applictationContext = App.mContext;
			instance.mSharedPreferences = applictationContext
					.getSharedPreferences(SHARE_DATA_FILE_NAME,
							Context.MODE_PRIVATE);
		}
		return instance;
	}

	public void saveInt(String key, int value) {
		getEditor().putInt(key, value).commit();
	}

	public void saveString(String key, String value) {
		getEditor().putString(key, value).commit();
	}

	public void saveBoolean(String key, boolean value) {
		getEditor().putBoolean(key, value).commit();
	}

	/**
	 * read the value from preference settings for the given key
	 * 
	 * @param key
	 *            which preference key to search for
	 * @param defValue
	 *            return when the given key not found, if not specified, "" will
	 *            return.
	 * @return the result value for the given key.
	 */
	public String getString(String key, String... defValue) {
		String defaultValue = "";
		if (null == defValue) {
			defaultValue = null;
		} else if (null != defValue && defValue.length > 0) {
			defaultValue = defValue[0];
		}
		return instance.mSharedPreferences.getString(key, defaultValue);
	}

	public int getInt(String key, Integer... defValue) {
		int defaultValue = -1;
		if (null == defValue) {
			defaultValue = -1;
		} else if (null != defValue && defValue.length > 0) {
			defaultValue = defValue[0];
		}
		return instance.mSharedPreferences.getInt(key, defaultValue);
	}

	public boolean getBoolean(String key, boolean... defValue) {
		boolean def = false;
		if (null != defValue && defValue.length > 0) {
			def = defValue[0];
		}
		return instance.mSharedPreferences.getBoolean(key, def);
	}

	public void remove(String key) {
		if (instance.mSharedPreferences.contains(key)) {
			getEditor().remove(key).commit();
		}
	}

	private Editor getEditor() {
		return instance.mSharedPreferences.edit();
	}

	public static void release() {
		instance = null;
	}
}